package leet;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 985. Sum of Even Numbers After Queries
 * 
 * <pre>
 * We have an array A of integers, and an array queries of queries.
 * 
 * For the i-th query val = queries[i][0], index = queries[i][1], we add val to
 * A[index]. Then, the answer to the i-th query is the sum of the even values of
 * A.
 * 
 * (Here, the given index = queries[i][1] is a 0-based index, and each query
 * permanently modifies the array A.)
 * 
 * Return the answer to all queries. Your answer array should have answer[i] as
 * the answer to the i-th query.
 * 
 * </pre>
 * 
 * @author zhujunbing
 * @date 2019年4月25日
 */
public class Leet0985 {
	

	public static void main(String[] args) {
		Leet0985 leet0985 = new Leet0985();
		int[] A = {1,2,3,4};
		int[][] queries = {{1,0},{-3,1},{-4,0},{2,3}};
		int[] sumEvenAfterQueries = leet0985.sumEvenAfterQueries(A, queries);
		for (int i : sumEvenAfterQueries) {
			System.out.println(i);
		}
	}

	/**
	 * <pre>
	 * Input: A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]] 
	 * Output: [8,6,2,4]
	 * Explanation: 
	 * At the beginning, the array is [1,2,3,4]. 
	 * After adding 1 to A[0], the array is [2,2,3,4], 
	 * and the sum of even values is 2 + 2 + 4 = 8.
	 * After adding -3 to A[1], the array is [2,-1,3,4], 
	 * and the sum of even values is 2 + 4 = 6. 
	 * After adding -4 to A[0], the array is [-2,-1,3,4], 
	 * and the sum of even values is -2 + 4 = 2. 
	 * After adding 2 to A[3], the array is [-2,-1,3,6], 
	 * and the sum of even values is -2 + 6 = 4.
	 * </pre>
	 * 
	 * 求偶数和
	 * 
	 * @param A
	 * @param queries
	 * @return
	 * @date 2019年4月25日
	 */
	public int[] sumEvenAfterQueries(int[] A, int[][] queries) {

		// if(queries==null|| queries.length==0) {
		//
		// }
		int[] ans = new int[queries.length];

		int sum = 0;

		for (int i : A) {
			if ((i & 1) == 0) {
				sum += i;
			}
		}

		for (int i = 0; i < queries.length; i++) {

			//
			int add = queries[i][0];
			int j = queries[i][1];
			int k = A[j];
			// 奇+奇
			if ((k & 1) == 1 && (add & 1) == 1) {
				sum += k + add;
			} else if ((k & 1) == 0 && (add & 1) == 1) {
				sum -= k;
			} else if ((k & 1) == 0 && (add & 1) == 0) {
				sum += add;
			}

			A[j] += add;
			ans[i]=sum;
		}

		return ans;
	}
}
